/**
 * 本文件使每个fd都有自己的缓冲区
 * 1. recv buffer
 * 2. send buffer
 */
#pragma once
#include <iostream>
#include <string>

#include <cstring>
#include <cerrno>

#include <sys/types.h>
#include <sys/socket.h>

#include "Log.hpp"

namespace MyConnection
{
    const static int rb_size = 1024;
    class Connection
    {
    public:
        Connection(int fd)
            : _fd(fd), _recv_buffer(std::string()), _send_buffer(std::string())
        {
        }
        ~Connection()
        {
        }
        void Recv()
        {
            // 要将在内核缓冲区的数据全部读上来
            char recv_buffer[rb_size];
            while (strlen(recv_buffer) != 0 && strlen(recv_buffer) == rb_size - 1)
            {
                // 采用非阻塞等待
                int recv_ret = recv(_fd, recv_buffer, sizeof(recv_buffer) - 1, MSG_DONTWAIT); 
                // 读成功了
                if(recv_ret > 0)
                {
                    recv_buffer[recv_ret] = 0;
                    _recv_buffer += recv_buffer;
                    // 处理本轮读上来的数据
                    Handle_Recv_Data();
                }
                // 对端关闭
                else if(recv_ret == 0)
                {   
                    _log.LogMessage(ClassFile, Info, "对端关闭, fd = %d\n", _fd);
                    
                }
                // 读取失败
                else
                {

                }
            }
        }
        void Send()
        {
        }
    private:
        // 处理本轮接收的数据
        void Handle_Recv_Data()
        {

        }
    private:
        int _fd;                  // 被打开的fd
        std::string _recv_buffer; // fd对应的recv_buffer
        std::string _send_buffer; // fd对应的send_buffer
    };
}